// 日志类 -> 单例

import 'dart:io';
import 'package:logging/logging.dart';

class AppLogger {
  static final AppLogger _instance = AppLogger._internal();
  late Logger _logger;
  File? _logFile;

  factory AppLogger() => _instance;
  AppLogger._internal();

  Future<void> init({Level level = Level.ALL}) async {
    Logger.root.level = level;
    _logger = Logger('App');

    // 监听日志记录
    Logger.root.onRecord.listen((LogRecord rec) {
      final String message = _formatLog(rec);
      print(message);
    });
  }

  String _formatLog(LogRecord rec) {
    return '${_formatTime(rec.time)} [${rec.level.name}] [${rec.loggerName}]: ${rec.message}'
        '${rec.error != null ? ' | ERROR: ${rec.error}' : ''}'
        '${rec.stackTrace != null ? '\n${rec.stackTrace}' : ''}';
  }

  String _formatTime(DateTime time) {
    return '${time.year}-${time.month.toString().padLeft(2, '0')}-${time.day.toString().padLeft(2, '0')} '
        '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}:${time.second.toString().padLeft(2, '0')}.${time.millisecond.toString().padLeft(3, '0')}';
  }

  // 通用日志方法
  void info(String msg) => _logger.info(msg);
  void warning(String msg) => _logger.warning(msg);
  void severe(String msg, [Object? error, StackTrace? stackTrace]) => _logger.severe(msg, error, stackTrace);
  void debug(String msg) => _logger.fine(msg);
  void verbose(String msg) => _logger.finer(msg);

  String? get logFilePath => _logFile?.path;
}